package com.example.demo.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 规格 JSON 工具类（通用版）
 * 输入为 Map<optionId, optionValueId>，输出标准化 spec_json 字符串
 * <p>
 * 示例：{1L→101L, 2L→201L} → {"1":101,"2":201}
 *
 * @author haochen78
 */
public class SpecJsonUtils {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 将规格映射转换为带尾逗号的扁平字符串，如 "1:101,2:201,"
     * 不排序，按 Map 的迭代顺序输出。
     *
     * @param map 规格映射，key=optionId, value=optionValueId
     * @return 格式为 "k1:v1,k2:v2,..." 的字符串；若为空则返回 ""
     */
    public static String mapToString(Map<Long, Long> map) {
        if (map == null || map.isEmpty()) {
            return "";
        }
        return map.entrySet().stream().map(e -> e.getKey() + ":" + e.getValue() + ",").collect(Collectors.joining(""));
    }

    /**
     * 判断两个扁平规格字符串是否逻辑相等（忽略顺序和空格）
     *
     * @param flat1 格式如 "1:101,2:201"
     * @param flat2 格式如 "2:201,1:101"
     * @return true 如果包含相同的 optionId → optionValueId 映射
     */
    public static boolean equalsIgnoreOrder(String flat1, String flat2) {
        Map<Long, Long> map1 = stringToMap(flat1);
        Map<Long, Long> map2 = stringToMap(flat2);
        return map1.equals(map2);
    }

    /**
     * 将 "1:101,2:201" 解析为 Map<Long, Long>
     */
    public static Map<Long, Long> stringToMap(String flat) {
        if (flat == null || flat.trim().isEmpty()) {
            return Collections.emptyMap();
        }

        // 兼容尾部逗号
        String clean = flat.endsWith(",") ? flat.substring(0, flat.length() - 1) : flat;
        if (clean.isEmpty()) {
            return Collections.emptyMap();
        }

        Map<Long, Long> map = new HashMap<>();
        for (String pair : clean.split(",")) {
            pair = pair.trim();
            if (pair.isEmpty()) {
                continue;
            }

            String[] parts = pair.split(":");
            if (parts.length != 2) {
                throw new IllegalArgumentException("无效格式: " + pair);
            }

            try {
                long key = Long.parseLong(parts[0].trim());
                long value = Long.parseLong(parts[1].trim());
                map.put(key, value);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("ID 必须为数字: " + pair, e);
            }
        }
        return map;
    }

}